package com.example.Controller;

import com.example.dao.RecordDao;
import com.example.dao.ToupiaoDao;
import com.example.dao.UserDao;
import com.example.pojo.Record;
import com.example.pojo.Toupiao;
import com.example.pojo.User;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/*
验证码
 */

@Controller
public class CommonController {
    public String name;
    public String code;
    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/common/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();
            code = verifyCode;
            System.out.println(code);
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @Autowired
    private UserDao userDao;

    @RequestMapping("/user/login")
    public String Login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        Model model, HttpSession session,HttpServletResponse response) {
        System.out.println(username);
        name = username;
        int temp = 0;
        List<User> all = userDao.findAll();
        model.addAttribute("emps", all);
        for (User user : all) {
            if (verifyCode.equals(code)) {
                if (user.getLoginName().equals(username) && user.getLoginPwd().equals(password)) {
                    temp = 1;
                    break;
                } else {
                    temp = 0;
                }
            } else {
                model.addAttribute("msg", "验证码错误");
                return "index";
            }
        }
        System.out.println(temp);
        if (temp == 1) {
            session.setAttribute("loginUser", username);
            if (username.equals("cqut")) {
                List<Record> all1 = recordDao.findAll();
                model.addAttribute("emps", all1);
                return "redirect:/admin";
            } else {
                return "redirect:/web";
            }
        } else {
            model.addAttribute("msg", "用户名或者密码错误");
            return "index";
        }
    }

    int flag = 0;
    @Autowired
    ToupiaoDao toupiaoDao;
    @Autowired
    RecordDao recordDao;

    public void setz() {
        List<Toupiao> all = toupiaoDao.findAll();
        for (Toupiao toupiao : all) {
            toupiao.setPiao("0");
            toupiaoDao.update(toupiao);
        }
    }

    @RequestMapping("/web")
    public String showAll(Model model) {
        if (flag == 0) {
            setz();
        }
        List<Toupiao> all = toupiaoDao.findAll();
        Collections.sort(all);
        model.addAttribute("emps", all);
        flag++;
        return "test";
    }

    @GetMapping("/web/{id}")
    public String to(@PathVariable("id") String id, Model model) {
        if (id.equals("0")) {
            List<Toupiao> all = toupiaoDao.findAll();
            Collections.sort(all);
            for (Toupiao toupiao : all) {
                if (!toupiao.getPiao().equals("0")) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    int insert = recordDao.insert(new Record(name, toupiao.getName(), toupiao.getPiao(),"", df.format(new Date())));
                    System.out.println(insert);
                }
            }
            setz();
            model.addAttribute("emps", all);
            model.addAttribute("m", "支付成功");
            return "dashboard";
        } else {
            System.out.println(name);
            Toupiao toupiao = toupiaoDao.find(id);
            Integer integer = Integer.parseInt(toupiao.getPiao()) + 1;
            String s = String.valueOf(integer);
            toupiao.setPiao(s);
            toupiaoDao.update(toupiao);
            List<Toupiao> all = toupiaoDao.findAll();
            Collections.sort(all);
            model.addAttribute("emps", all);
            return "test";
        }
    }

    @GetMapping("/de/{id}")
    public String de(@PathVariable("id") String id, Model model) {
        if (id.equals("0")) {
            List<Toupiao> all = toupiaoDao.findAll();
            for (Toupiao toupiao : all) {
                if (!toupiao.getPiao().equals("0")) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    int insert = recordDao.insert(new Record(name, toupiao.getName(), toupiao.getPiao(),"", df.format(new Date())));
                    System.out.println(insert);
                }
            }
            setz();
            Collections.sort(all);
            model.addAttribute("emps", all);
            model.addAttribute("m", "支付成功");
            return "dashboard";
        } else {
            System.out.println(name);
            Toupiao toupiao = toupiaoDao.find(id);
            if (Integer.parseInt(toupiao.getPiao()) > 0) {
                Integer integer = Integer.parseInt(toupiao.getPiao()) - 1;
                String s = String.valueOf(integer);
                toupiao.setPiao(s);
                toupiaoDao.update(toupiao);
                List<Toupiao> all = toupiaoDao.findAll();
                Collections.sort(all);
                model.addAttribute("emps", all);
                return "test";
            } else {
                List<Toupiao> all = toupiaoDao.findAll();
                Collections.sort(all);
                model.addAttribute("emps", all);
                model.addAttribute("m", id+"的数量为0不能再减少了");
                return "test";
            }


        }
    }

    @RequestMapping("/main.html")
    public String show(Model model) {
        List<Toupiao> all = toupiaoDao.findAll();
        Collections.sort(all);
        double AllPrice = 0;
        for (Toupiao toupiao : all) {
            AllPrice = AllPrice + toupiaoDao.findPrice(toupiao.getId()) * Integer.parseInt(toupiao.getPiao());
        }
        model.addAttribute("emps", all);
        String s = String.valueOf(AllPrice);
        s = "您一共消费" + s;
        model.addAttribute("msg", s);
        return "dashboard";
    }

    @RequestMapping("/record")
    public String record(Model model) {
        List<Record> records = recordDao.find(name);
        model.addAttribute("emps", records);
        return "record";
    }

    @GetMapping("/willBorrowBook/{id}")
    public String allMoney(@PathVariable("id") String id, Model model) {
        int temp=0;
        if (id.equals("0")){
            List<Toupiao> all = toupiaoDao.findAll();
            for (Toupiao toupiao : all) {
                if (!toupiao.getPiao().equals("0")){
                    temp=1;
                    break;
                }
                else {
                    temp=0;
                }
            }
            System.out.println(temp);
            if (temp==1) {
                for (Toupiao toupiao : all) {
                    if (!toupiao.getPiao().equals("0")) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        Record record = new Record(name, toupiao.getName(), toupiao.getPiao(), "1", df.format(new Date()));
                        System.out.println(record.toString());
                        int insert = recordDao.insert(new Record(name, toupiao.getName(), toupiao.getPiao(),"1", df.format(new Date())));
                        System.out.println(insert);
                    }
                }
                setz();
                model.addAttribute("emps", all);
                Collections.sort(all);
                model.addAttribute("msg", "借阅成功，要爱惜书哦！");
            }
            else {
                model.addAttribute("emps", all);
                Collections.sort(all);
                model.addAttribute("msg", "快去借书，活到老学到老");
            }
        }
        return "/borrow/willBorrowBook";
    }
    @RequestMapping("/state")
    public String bookState(Model model){
        List<Record> byKind = recordDao.findByKind(name,"1");
        for (Record record : byKind) {
            record.setKind("未归还");
        }
        model.addAttribute("emps",byKind);
        return "borrow/borrowState";
    }
    @RequestMapping("before")
    public String beforeState(Model model){
        List<Record> byKind = recordDao.findByKind(name,"2");
        for (Record record : byKind) {
            record.setKind("已经归还");
        }
        model.addAttribute("emps",byKind);
        return "borrow/beforeBorrow";
    }
}

